package pl.pasu.ocrtc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DrawingPanelActivity extends Activity implements OcrDoneCallback {

    private static final String TAG = "DrawingPanelActivity";
    private static final String SHOW_KEYBOARD_PREF_KEY = "pref.show_keyboard";
    private static final String AFTER_FIRST_RUN_PREF_KEY = "pref.first_run";
    private OcrEngine ocr;
    private DrawPanel drawPanel;
    private LinearLayout keyboardPanel;
    private LinearLayout textPanel;
    private TextView textLabel;
    private boolean showKeyboard;
    private boolean afterFirstRun;
    private enum TimeEnum {
        H, M, S, TIME
    };
    private TimeEnum timeEnum;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferencesHandler.initPreferences(this);
        showKeyboard = SharedPreferencesHandler.getBooleanPreference(SHOW_KEYBOARD_PREF_KEY);
        afterFirstRun = SharedPreferencesHandler.getBooleanPreference(AFTER_FIRST_RUN_PREF_KEY);
        if (!afterFirstRun) {
            SharedPreferencesHandler.savePreference(AFTER_FIRST_RUN_PREF_KEY, true);
        } else {
            // TODO show info dialog
        }
        ocr = new BuildInEngine(this);
        // ocr = new RemoteOcrEngine();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.drawing_panel);
        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.buttonH :
                        timeEnum = TimeEnum.H;
                        if (!showKeyboard) {
                            ocr.readImage(drawPanel.getBitmapFromCanvas(), DrawingPanelActivity.this);
                        } else {
                            proceedAfterKeyboard(textLabel.getText().toString());
                        }
                        break;
                    case R.id.buttonM :
                        timeEnum = TimeEnum.M;
                        if (!showKeyboard) {
                            ocr.readImage(drawPanel.getBitmapFromCanvas(), DrawingPanelActivity.this);
                        } else {
                            proceedAfterKeyboard(textLabel.getText().toString());
                        }
                        break;
                    case R.id.buttonS :
                        timeEnum = TimeEnum.S;
                        if (!showKeyboard) {
                            ocr.readImage(drawPanel.getBitmapFromCanvas(), DrawingPanelActivity.this);
                        } else {
                            proceedAfterKeyboard(textLabel.getText().toString());
                        }
                        break;
                    case R.id.buttonT :
                        timeEnum = TimeEnum.TIME;
                        if (!showKeyboard) {
                            ocr.readImage(drawPanel.getBitmapFromCanvas(), DrawingPanelActivity.this);
                        } else {
                            proceedAfterKeyboard(textLabel.getText().toString());
                        }
                        break;
                    case R.id.clear :
                        drawPanel.clearImage();
                        textLabel.setText("");
                        break;
                }
            }
        };
        Button h = (Button) findViewById(R.id.buttonH);
        Button m = (Button) findViewById(R.id.buttonM);
        Button s = (Button) findViewById(R.id.buttonS);
        Button t = (Button) findViewById(R.id.buttonT);
        Button clear = (Button) findViewById(R.id.clear);
        h.setOnClickListener(listener);
        m.setOnClickListener(listener);
        s.setOnClickListener(listener);
        t.setOnClickListener(listener);
        clear.setOnClickListener(listener);
        drawPanel = (DrawPanel) findViewById(R.id.draw_panel);
        keyboardPanel = (LinearLayout) findViewById(R.id.buttons_panel);
        textPanel = (LinearLayout) findViewById(R.id.main_text_wrap);
        textLabel = (TextView) findViewById(R.id.main_text);
        setUIElementsVisibility();
    }

    private void setUIElementsVisibility() {
        if (showKeyboard) {
            textPanel.setVisibility(View.VISIBLE);
            drawPanel.setVisibility(View.GONE);
            keyboardPanel.setVisibility(View.VISIBLE);
        } else {
            textPanel.setVisibility(View.GONE);
            drawPanel.setVisibility(View.VISIBLE);
            keyboardPanel.setVisibility(View.GONE);
        }
    }

    @Override
    public void onOcrDone(final String recognizedText) {
        Logger.i(TAG, "onOcrDone recognizedText=" + recognizedText);
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (recognizedText.length() == 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(DrawingPanelActivity.this);
                    builder.setMessage("Unable to recognize text").setCancelable(true);
                    AlertDialog d = builder.create();
                    d.setCanceledOnTouchOutside(true);
                    d.show();
                } else {
                    String preText = "Set alarm after ";
                    String timeText = null;
                    if (timeEnum == TimeEnum.H) {
                        timeText = " hour(s) ?";
                    } else if (timeEnum == TimeEnum.M) {
                        timeText = " minute(s) ?";
                    } else if (timeEnum == TimeEnum.S) {
                        timeText = " second(s)";
                    } else if (timeEnum == TimeEnum.TIME) {
                        preText = "Set alarm at ";
                        timeText = " ?";
                    }
                    AlertDialog d = DialogFactory.createYesNoNeutralDialog(DrawingPanelActivity.this, preText + recognizedText
                            + timeText, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setAlarmAt(recognizedText, timeEnum);
                            dialog.cancel();
                        }
                    }, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            drawPanel.clearImage();
                            textLabel.setText("");
                        }
                    }, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            showKeyboard = true;
                            setUIElementsVisibility();
                            textLabel.setText(recognizedText);
                        }
                    });
                    d.show();
                }
            }
        });
    }

    private void proceedAfterKeyboard(final String text) {
        String preText = "Set alarm after ";
        String timeText = null;
        if (timeEnum == TimeEnum.H) {
            timeText = " hour(s) ?";
        } else if (timeEnum == TimeEnum.M) {
            timeText = " minute(s) ?";
        } else if (timeEnum == TimeEnum.S) {
            timeText = " second(s)";
        } else if (timeEnum == TimeEnum.TIME) {
            preText = "Set alarm at ";
            timeText = " ?";
        }
        AlertDialog d = DialogFactory
                .createYesNoDialog(DrawingPanelActivity.this, preText + text + timeText, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setAlarmAt(text, timeEnum);
                        dialog.cancel();
                    }
                }, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        d.show();
    }

    private void setAlarmAt(String timeStr, TimeEnum timeType) {
        Logger.i(TAG, "setAlarmAt " + timeStr + timeType);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.getItem(1).setTitle(showKeyboard ? "Show drawing panel" : "Show keyboard");
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        // Handle item selection
        if (item.getItemId() == R.id.menu_settings) {
        } else if (item.getItemId() == R.id.menu_toggle_keyboard) {
            showKeyboard = !showKeyboard;
            setUIElementsVisibility();
        }
        return true;
    }
}
